﻿using Microsoft.AspNetCore.Mvc;
using orm.sqlsugar.api.Entities;
using SqlSugar;

namespace orm.sqlsugar.api.Controllers
{
    /// <summary>
    /// 分表操作
    /// </summary>
    public class SplitTableController(ISqlSugarClient sqlSugarClient) 
        : SqlSugarBaseController(sqlSugarClient)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var users = new List<User> 
            {
                new() { Name = "hechenyu", CreateTime = Convert.ToDateTime("2025-1-1") },
                new() { Name = "hechenyu", CreateTime = Convert.ToDateTime("2025-1-1") },
                new() { Name = "hechenyu", CreateTime = Convert.ToDateTime("2025-1-2") },
            };

            return Ok(await SqlSugarClient
                .Insertable(users)
                .SplitTable()
                .ExecuteReturnSnowflakeIdListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> List_Interval(DateTime startDate, DateTime endDate)
        {
            // 按时间区间查询（本质上是生成表名去 union）
            return Ok(await SqlSugarClient
                .Queryable<User>()
                .SplitTable(startDate, endDate)
                .ToListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> List_Recently(int take)
        {
            // 查询时间距离现在最近的 n 张表
            return Ok(await SqlSugarClient
                .Queryable<User>()
                .SplitTable(list => list.Take(take))
                .ToListAsync());
        }

        [HttpGet]
        public async Task<IActionResult> List_Assign(DateTime date)
        {
            // 查询指定的表（支持多个值）
            var tb = SqlSugarClient.SplitHelper<User>().GetTableName(date);
            return Ok(await SqlSugarClient
                .Queryable<User>()
                .SplitTable(list => list.InTableNames(tb))
                .ToListAsync());
        }
    }
}
